#!/bin/bash

# if error, exit immediately
set -e

# config params
# convert size
# 1 MiB ≈ 1.049 MB​
# ​1 MB ≈ 0.954 MiB
# img disk size
IMG_SIZE="270M"
# boot partition size is 256MiB. (vmlinuz、initrd.img、grub.cfg)
BOOT_SIZE="256M"
# Note: boot partition is 257MiB. Otherwise Error: The location 257MiB is outside of the device
IMG_BOOT_SIZE="257MiB"
# img format
IMG_FORMAT="raw"
# mount point
TARGET_MOUNT="/mnt/prod_boot"
# kernel version
KERNEL_VERSION="6.1.0-35"
# CPU architecture
ARCH="amd64"
# product version
PROD_VERSION="1.0.0"
# img name
IMG_NAME="auto_prod_legacy_boot_${ARCH}"
# img file
IMG_FILE="${IMG_DIR}/${IMG_NAME}_${BOOT_SIZE}.img"

# create img file
if [ -f ${IMG_FILE} ]; then
    echo "Remove old img file: ${IMG_FILE} ..."
    rm -f ${IMG_FILE}
fi
echo "create img file: ${IMG_FILE}"
qemu-img create -f "$IMG_FORMAT" "$IMG_FILE" "$IMG_SIZE"
echo "create img file:$(du -h "$IMG_FILE") is created successfully."
# get loop device and related partition
LOOP_DEV=$(losetup --find --show "$IMG_FILE")
echo "related loop device: $LOOP_DEV"

# create partition table
# create MBR partition
parted -s "$LOOP_DEV" mklabel msdos
# /boot partition
parted -s "$LOOP_DEV" mkpart primary ext4 1MiB "${IMG_BOOT_SIZE}"
# set boot flag
parted -s "$LOOP_DEV" set 1 boot on
# refresh partition table
partprobe "$LOOP_DEV"
echo "prod boot img:${IMG_FILE} MBR partition is done"
# get the boot partition related loop device
BOOT_PART="${LOOP_DEV}p1"

# mkfs.ext4 boot partition
echo "mkfs.ext4 boot partition:${BOOT_PART} ..."
mkfs.ext4 "$BOOT_PART"

# mount boot partition
if [ -d ${TARGET_MOUNT} ]; then
    echo "remove old mount dir ${TARGET_MOUNT}"
    rm -rf ${TARGET_MOUNT}
fi

mkdir -p "${TARGET_MOUNT}"
mount "$BOOT_PART" "${TARGET_MOUNT}"
echo "mount boot part:$BOOT_PART to ${TARGET_MOUNT}..."

# copy{initrd_prod.img、vmlinuz_prod、grub.cfg}
echo "copy initrd_prod.img..."
cp ${TMP_DIR}/initrd_prod.img-${PROD_VERSION}-${ARCH} ${TARGET_MOUNT}/initrd_prod.img-${PROD_VERSION}-${ARCH}
echo "copy vmlinuz_prod..."
cp ${WORK_DIR}/kernel/vmlinuz-${KERNEL_VERSION}-${ARCH} ${TARGET_MOUNT}/vmlinuz_prod-${PROD_VERSION}-${ARCH}
echo "copy grub_legacy.cfg..."
mkdir -p "${TARGET_MOUNT}/grub"
cp ${WORK_DIR}/grub/grub_legacy.cfg ${TARGET_MOUNT}/grub/grub.cfg

# sync data write to disk
sync

echo "install grub i386-pc..."
grub-install \
    --target=i386-pc \
    --boot-directory=${TARGET_MOUNT} \
    --modules="part_msdos fat ext2" \
    ${LOOP_DEV}

# sync data write to disk
sync

echo "cleaning up..."
# umount boot partition
umount "$BOOT_PART"
# remove loop device
losetup -d "$LOOP_DEV"
# remove kpartx mapping
kpartx -d "$LOOP_DEV"
echo "remove loop dev: $LOOP_DEV"

echo "prod boot image is created successfully at ${IMG_FILE}."
